<template>
	<view class="content">
		<view v-if="show">
			<view>
				<view style="width: 100%;padding-top: 100rpx;" v-if="detal != ''">
					<!-- <u-section title="内容说明" :right="false" color="#f5991e" style="margin-bottom: 30rpx; margin-top: 0rpx;" font-size="28" ></u-section> -->
					<view :style="'height: '+ contentheight+';overflow: hidden;'" >
						<u-parse :html="detal" :lazy-load="true" :show-with-animation='true' :selectable='true'></u-parse>
					</view>
					<view class="u-flex-col u-col-center" @click="lookcontent">
						<u-icon :name="contenticonname" size="38" color="#f5991e"></u-icon>
						<text style="font-size: 20rpx;color: #888;">{{contenticonname=='arrow-down'?'查看更多':'点击收起'}}</text>
					</view>
				</view>
				
			</view>
			<view class="content-1">
				<u-input v-model="text" type="textarea" :border="false" height="200" :auto-height="true" maxlength='999'/>
				
				<view>
					<view class="u-flex" style="flex-wrap: wrap">
						<view v-for="(item,index) in url":key="index" class="u-flex" >
							<view v-if="item.type.includes('image')" class="u-flex" style="justify-content: center">
								<view style="position: absolute;z-index: 12;" v-if="!item.complete">
									<u-circle-progress active-color="#55aaff" :percent="item.progress" :width="imgwidth" bgColor="rgba(255, 255, 255, 0)" :border-width='10'>
										<text class='u-progress-info' >{{item.progress}}</text>
									</u-circle-progress>
								</view>
								<view style="position: relative;z-index: 1">
									<view style="position: absolute; right: 0;z-index: 1;" @click="remove(item)" v-if="item.complete">
										<u-icon name="close" ></u-icon>
									</view>
									<view v-if="!item.complete"  :style="'background-color: rgba(0,0,0,0.8);position: absolute;z-index: 9;'+'width:'+imgwidth+'px;height:'+imgwidth+'px;margin:8rpx;'"></view>
									<image :style="'width:'+imgwidth+'px;height:'+imgwidth+'px;margin:8rpx;'" :src="item.url" mode="aspectFill" @click="previewImg(index)"></image>
								</view>
								
							</view>
							<view v-if="item.type.includes('video')" class="u-flex" style="justify-content: center">
								<view style="position: absolute;z-index: 12;" v-if="!item.complete">
									<u-circle-progress active-color="#55aaff" :percent="item.progress" :width="imgwidth" bgColor="rgba(255, 255, 255, 0)" :border-width='10'>
										<text class='u-progress-info' >{{item.progress}}</text>
									</u-circle-progress>
								</view>
								<view style="position: relative;z-index: 1">
									<view v-if="!item.complete"  :style="'background-color: rgba(0,0,0,0.8);position: absolute;z-index: 9;'+'width:'+imgwidth+'px;height:'+imgwidth+'px;margin:8rpx;'"></view>
									<view style="position: absolute; right: 0;z-index: 1;" @click="remove(item)" v-if="item.progress==100">
										<u-icon name="close" ></u-icon>
									</view>
									<zetank-Dynamic-video :videoUrl='item.url' :w='imgwidth' :h='imgwidth' style="margin:8rpx;"></zetank-Dynamic-video>
								</view>
							</view>
							
						</view>
					</view>
					
				</view>
				<view class="u-flex" style="border-top: 1px solid #efefef;padding: 20rpx;border-bottom: 1px solid #efefef;padding: 20rpx">
					<view class="u-flex-3">
						
					</view>
					<view class="u-flex-2 u-flex u-row-center" @click="chooseImage">
						<u-icon name="photo" size="40rpx" color="#4baed5"></u-icon>
						<text style="margin-left: 10rpx;color: #4baed5;">图片</text>
					</view>
					<view class="u-flex-2 u-flex u-row-center" @click="chooseVideo">
						<u-icon name="play-right" size="40rpx" color="#f5991e"></u-icon>
						<text style="margin-left: 10rpx;color: #f5991e;">视频</text>
					</view>
				</view>
			
			
			</view>
			
			<view  style="font-size: 20rpx;line-height: 18rpx;height: auto;color: #959595;padding: 20rpx;margin-bottom: 100rpx;">
				<text style="line-height: 10rpx;">
					1、视频文件过大时压缩时间较长，请耐心等待\n
					2、若出现黑屏，请清理手机内存\n
					3、建议您调整手机拍摄清晰度选择720p及以下的规格进行拍摄\n
					4、图片+视频最多添加9条，每个视频≤600s
				</text>
				
			</view>
			<view :style="'width:'+btheight">
				<button @click="sumbit"class="btu" style="background-color: #4baed5;color: #FFFFFF;">提交</button>
			</view>
			<zetank-backBar textcolor="#000" :showLeft="true" :showTitle="false" navTitle='标题'></zetank-backBar>
		</view>
		<w-compress ref='wCompress' />
	</view>
</template>

<script>
	export default {
		name:"upfiles",
		data() {
			return {
				btheight:'100%',
				text:'',
				imgwidth:'',
				url:[],
				num:0,
				imgurl:[],
				videourl:[],
				border:false,
				calendarshow:false,
				btheight:"100%",
				buttontrue:false,
				tasklist:[],
				contentheight:'200rpx',
				contenticonname:'arrow-down',

			};
		},
		created() {
			let windowWidth =uni.getSystemInfoSync().windowWidth
			if(windowWidth>960){
				this.btheight="750px"
				this.imgwidth=300
			}else{
				this.imgwidth=windowWidth/3.9
			}
		},
		mounted() {
			if(this.type===1){
				this.$refs.uForm.setRules(this.rules);
			}
			
		},
		props:{
			show:{
				type:Boolean,
				default:true
			},
			detal:{
				type:String,
				default:''
			},
			TXcos:{
				type:Object,
			}
		},
		methods:{
			chooseImage(){
				uni.chooseImage({
					count: 9,
					success: res => {
						console.log(res);
						this.upimg(res)
					},
				})
			},
			chooseFiles(){
				const _this = this;
				  uni.chooseFile({
					success (res) {
					  // console.log('chooseFiles',res);
					  /* 判断选择的文件类型*/
					  if(res.tempFilePaths.length>0){
						  let img = {tempFilePaths:[],tempFiles:[]}
						  let video = {tempFilePaths:[],tempFiles:[]}
						  for(let i =0;i<res.tempFilePaths.length;i++){
						  	if(res.tempFiles[i].type.includes('image')){
						  		img.tempFiles.push(res.tempFiles[i])
						  		img.tempFilePaths.push(res.tempFilePaths[i])
						  	}else if (res.tempFiles[i].type.includes('video')){
						  		video.tempFiles.push(res.tempFiles[i])
						  		video.tempFilePaths.push(res.tempFilePaths[i])
						  	}
						  }
						  // console.log('img',img);
						  if(img.tempFilePaths.length >0){
							  _this.upimg(img);
						  }
						  // console.log('video',video);
						  if(video.tempFilePaths.length >0){
						  	 _this.upvideo(video);
						  }
					  }
						
					}
				})
			},
			chooseVideo(){
				let _this = this
				let video = {tempFilePaths:[],tempFiles:[]}
				uni.chooseVideo({
					count: 1,
					sourceType: ['album', 'camera'],
					compressed:true,
					success:async function(e) {
						video.tempFilePaths.push(e.tempFilePath)
						video.tempFiles.push(e.tempFile)
						_this.upvideo(video);
					},
				})
			},
			/* 图片压缩 */
			async imgcompress(tempFilePaths,type){
				let res = await this.$refs.wCompress.start(tempFilePaths, {
					pixels: 1000000,  // 最大分辨率，默认二百万
					quality: 0.8,     // 压缩质量，默认0.8
					type,      // 图片类型，默认jpg
					base64: true,     // 是否返回base64，默认false，非H5有效
				  }).catch((err)=>{return err})
				  return res
				
			},
			/* 图片上传 */
			async upimg(res){
				if(!res.tempFilePaths.length){
					return
				}
				let starnum = this.num
				// console.log("选择",res);
				for(let i=0;i<res.tempFilePaths.length;i++){
					let index = this.url.push({
						url:res.tempFilePaths[i],
						progress:0,
						type:res.tempFiles[i].type,
						id:starnum+i,
						name:res.tempFiles[i].name,
						complete:false
					})-1
					let type = res.tempFiles[i].type.split("/")[1]
					let size = res.tempFiles[i].size
					let url = res.tempFilePaths[i]
					if(type != 'gif'){
						let e = await this.imgcompress(res.tempFilePaths[i],type)
						size = e.size
						url = e.url
						// console.log(e);
					}
					// console.log(size);
					let _this = this
					await uniCloud.uploadFile({
						filePath: url,
						cloudPath: res.tempFiles[i].name,
						onUploadProgress: function(progressEvent) {
							// console.log("进程",progressEvent);
							_this.setProgress(progressEvent,index)
						},
						success:(result)=>{
							_this.url[index].complete=true
							// console.log(_this.url[indx]);
							let data = {
								url:result.fileID,
								id:starnum+i,
								name:res.tempFiles[i].name,
								type:res.tempFiles[i].type,
								size	
							}
							_this.imgurl.push(data)
							// console.log(_this.imgurl);
							this.$emit('success',data)
						}
					});
				}
				this.num = res.tempFilePaths.length + this.num
			},
				
				setProgress(progressEvent,indx) {
					const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total)
					this.url[indx].progress=parseInt(percentCompleted)		
					this.$emit('progress',this.url)
				},
				async upvideo(e){
					console.log('upvideo',e);
					if(!e.tempFilePaths.length){
						return
					}
					let _this = this
					for(let i=0;i<e.tempFilePaths.length;i++){
						_this.url.push({
							id:_this.num+i,
							url:e.tempFilePaths[i],
							progress:0,
							type:"video",
							size:e.tempFiles[i].size,
							name:e.tempFiles[i].name,
							complete:false
						})
					}
					console.log(_this.url);
					let starnum = _this.num
					_this.num = _this.num + e.tempFilePaths.length
					for (let i =0;i<e.tempFilePaths.length;i++){
						if(_this.TXcos){
							_this.uploadvideo_TXcos(e.tempFiles[i],starnum+i,'.mp4');
						}else{
							console.log('无',_this.TXcos);
							console.log(e);
							// return
							const result = await uniCloud.uploadFile({
								filePath: e.tempFilePaths[i],
								cloudPath: e.tempFiles[i].name,
								onUploadProgress: function(progressEvent) {
									// console.log("进程",progressEvent);
									let indx = _this.url.findIndex(item => item.url==e.tempFilePaths[i])
									_this.setProgress(progressEvent,indx)
								},
								success:(res)=>{
									// console.log('上传',res);
									let indx = _this.url.findIndex(item => item.url==e.tempFilePaths[i])
									_this.url[indx].complete=true	
									let data = {
										url:res.fileID,
										id:_this.url[indx].id,
										name:_this.url[indx].name,
										type:_this.url[indx].type,
										size:_this.url[indx].size,
										
									}
									_this.videourl.push(data)
									console.log(_this.videourl);
									_this.$emit('success',data)
							
								}
							});
						}
					}
					
							

				},
				// 腾讯云cos上传方法
				uploadvideo_TXcos(url,idx,type) {
					console.log("上传");
					let Key= this.createUniqueId(1)[0]+type;
					let _this = this;
					var COS = require('../../js_sdk/cos-js-sdk-v5');
					var cos = new COS({
						SecretId: _this.TXcos.SecretId,
						SecretKey: _this.TXcos.SecretKey,
						});
					cos.uploadFile({
					   Bucket: _this.TXcos.Bucket, /* 必须 */
					   Region: _this.TXcos.Region,     /* 存储桶所在地域，必须字段 */
					   Key: Key,              /* 必须 */
					   Body: url,                /* 必须 */
					   SliceSize: 1024 * 1024 * 1,     /* 触发分块上传的阈值，超过5MB使用分块上传，非必须 */
					   onTaskReady: function(taskId) {                   /* 非必须 */
						   
						   _this.tasklist.push({
							   taskId:taskId,
							   id:idx
						   })
					   },
					   onProgress: function (progressData) {           /* 非必须 */
							for(let i=0;i<_this.url.length;i++){
								if(_this.url[i].id==idx){
									_this.url[i].progress=parseInt(progressData.percent*100)
								}
							}
						    _this.$emit('progress',_this.url)
					   },
					   onFileFinish: function (err, data, options) {
						  console.log(options.Key + '上传' + (err ? '失败' : '完成'));
					   },
						}, function(err, data) {
						   console.log(err || data);
						   if(data){
							   let arr = []
							  let a = 'https://' +data.Location
							  arr.push({
								  url:a,
								  id:idx,
							  })
							 
							  _this.videourl=[..._this.videourl,...arr]
							  _this.$emit('success',_this.videourl)
						   }
					});
				},
				// 附带生成随机文件名的方法，也可以替换成你自己的
				createUniqueId(n) {
					var random = function() { // 生成10-12位不等的字符串
						return Number(Math.random().toString().substr(2)).toString(36); // 转换成十六进制
					};
					var arr = [];
				
					function createId() {
						var num = random();
						var _bool = false;
						arr.forEach(v => {
							if (v === num) _bool = true;
						});
						if (_bool) {
							createId();
						} else {
							arr.push(num);
						}
					}
					var i = 0;
					while (i < n) {
						createId();
						i++;
					}
					return arr;
				},
				sumbit(){
					console.log('sumbit');
					uni.showLoading({
						icon:'loading'
					})
					let count = 0
					if(this.url.length>0){
						for(let i =0;i<this.url.length;i++){
							if(this.url[i].progress<100){
								count ++
							}
	
						}
						if(count >0){
							uni.showLoading({
								title:"上传中，请稍等"
							})
							setTimeout(()=>{
								uni.hideLoading()
								count = 0
							},2000)
						
						}else{
							if(this.url.length == this.imgurl.length+this.videourl.length){
								this.imgurl= this.imgurl.map((item) => item.url)
								this.$emit("complete",this.text,this.imgurl,this.videourl)
								
							}else{
								uni.showLoading({
									title:"数据整合中，请稍等"
								})
								setTimeout(()=>{
									uni.hideLoading()
								},1000)
							}
						}
					}else if(this.url.length==0 && this.text!=''){
						this.$emit("complete",this.text,this.imgurl,this.videourl,this.model)
					}else if(this.url.length==0 && this.text==''){
						uni.showLoading({
							title:"请完成上传"
						})
						
						setTimeout(()=>{
							uni.hideLoading()
						},2000)
					}
					
					
					
					
				},
				calendarchange(e){
					console.log('时间',e)
					this.model.when=e.result
				},
				previewImg(index){
					let imgList = this.url.filter((item,index,array) => item.type.includes('image'))
					imgList= imgList.map((item) => item.url)
					uni.previewImage({
						current:index,
						urls:imgList,
						longPressActions: {
							itemList: ['保存图片'],
						}
					})
				},
				remove(data){
					console.log(data);
					if(data.type.includes('image')){	
						let num = this.imgurl.findIndex(item => item.id == data.id)
						console.log('num',num);
						if(num != -1){
							this.imgurl=this.imgurl.filter(item => item.id != data.id)
							let dix = this.url.findIndex(item => item.id == data.id)
							this.url.splice(dix,1)			
						}else{
							uni.showLoading({
								title:"删除失败，请稍等"
							})
							setTimeout(()=>{
								uni.hideLoading()
							},1000)
						}
	
					}
					
					if(data.type.includes('video')){
						let num =0
						for(let i=0;i<this.videourl.length;i++){
							if(this.videourl[i].id==data.id){
								num ++
							}
						}
						console.log('num',num);
						if(num>0){
							this.videourl=this.videourl.filter(item => item.id != data.id)
							let dix = 0
							for(let i=0;i<this.url.length;i++){
								if(this.url[i].id==data.id){
									dix=i
								}
							}
							this.url.splice(dix,1)
					
							if(this.TXcos){
								let taskId=''
								for(let i=0;i<this.tasklist.length;i++){
									if(this.tasklist[i].id==data.id){
										taskId=this.tasklist[i].taskId
									}
								}
								var COS = require('../../js_sdk/cos-js-sdk-v5');
								var cos = new COS({
									SecretId: this.TXcos.SecretId,
									SecretKey: this.TXcos.SecretKey,
									});
								
								cos.cancelTask(taskId)	
							}
							
							
						}else{
							uni.showLoading({
								title:"删除失败，请稍等"
							})
							setTimeout(()=>{
								uni.hideLoading()
							},1000)
						}
						
					}
				},
				lookcontent(){
					if(this.contentheight=='200rpx'){
						this.contentheight='auto',						this.contenticonname='arrow-up'
					}else{
						this.contentheight='200rpx',
						this.contenticonname='arrow-down'
					}
				}

			}
			
		}
	
</script>

<style>
	.btu{
		position:fixed;
		bottom: 0;
		height: 80rpx;
		width: 100%;
		background-color: #0FAEFF;
		color: #FFFFFF;
	}
	.content-1{
		margin: 20rpx 10rpx;
		padding: 15rpx 15rpx;
		border-top: 1px solid #efefef;
		
	}
	.u-progress-info {
			font-size: 3rpx;
			color: #FFFFFF;
		
	}
	
</style>
